package com.emm.yixun.website.controller.call;

//框架包
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.CallCustomerInfo;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.system.service.TelRecordServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.ConstantConfig;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.call.CallCustomerService;
//变化的引用
import com.emm.yixun.common.model.CallCustomer;
import com.emm.yixun.common.model.dto.CallCustomerDto;
import com.emm.yixun.common.model.dto.CustomerComponentDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.ImportStatisticsDto;
import com.emm.yixun.common.model.dto.TelRecordDto;
import com.emm.yixun.customer.service.CallCustomerServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;

@Controller
@RequestMapping("/call/callCustomer/")
public class CallCustomerController extends BaseController<CallCustomer> {

	@Autowired
	private CallCustomerServiceFacade callCustomerServiceFacade;
	@Autowired
	private CallCustomerService callCustomerService;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private TelRecordServiceFacade telRecordServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private ConstantConfig constantConfig;

	@RequestMapping(value = "callCustomerList")
	public String index(HttpServletRequest request, ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			String status = request.getParameter("status");
			if (StringUtils.isBlank(status)) {
				status = "0";
			}
			map.put("status", status);
			map.put("impId", request.getParameter("impId"));
			return "/call/callCustomerList";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "callImport")
	public String callImport(ModelMap map) {
		map.put("callTemplet", constantConfig.getCallTemplet());
		return "/call/import";
	}

	// call导入
	@RequestMapping(value = "uploadExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes uploadExcel(HttpServletRequest request, MultipartFile file) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用新增接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:import"))) {
			try {
				logger.debug("excel title===" + request.getParameter("title"));
				String title = request.getParameter("title");
				logger.debug("excel fileName===" + file.getOriginalFilename());
				String fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
				boolean flag = fileType(suffix);
				if (!flag) {
					ar.setFailMsg("请上传正确的excel文件");
					return ar;
				}
				logger.debug("开始导入excel===start");
				Response<ImportStatisticsDto> res = callCustomerService.uploadExcel(title, file.getInputStream(),
						suffix);
				logger.debug("excel导入结束===end===" + res.isSuccess());
				if (res.isSuccess()) {
					ar.setRes(Const.SUCCEED);
					ar.setSucceed(res);
				}
			} catch (Exception e) {
				logger.debug("call客导入报错====》", e);
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 判断是否为excel
	public boolean fileType(String suffix) {
		boolean flag = true;

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < suffix.length(); i++) {
			char c = suffix.charAt(i);
			sb.append(Character.toLowerCase(c));
		}

		if ("xls|xlsx".indexOf(sb.toString()) < 0) {
			flag = false;
		}
		return flag;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(CallCustomerDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限 2.调用新增接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<CallCustomerDto> response = callCustomerServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用查看接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:view"))) {
			try {
				Response<CallCustomerInfo> response = callCustomerServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(CallCustomerDto dto, String visitDate, String projectId) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用修改接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:callPhone"))) {
			try {
				// 判断是否有主键
				if (dto.getId() == null) {
					ar.setFailMsg("系统错误");
					logger.error("id为空");
					return ar;
				}

				User user = ShiroUtil.getCurrentUser();
				dto.setUpdateUserId(user.getId()); // 修改人
				dto.setVisitTime(DateUtils.StringToDate(visitDate, DateStyle.YYYY_MM_DD)); // 到访日期

				int callNum = Integer.parseInt(dto.getCallNum()); // 沟通次数

				// List<TelRecordDto> telList = new ArrayList();
				TelRecordDto telDto = new TelRecordDto();
				telDto.setRelationId(dto.getId());
				telDto.setRelationType("1");
				telDto.addDesc("create_time");
				ResponseList<TelRecordDto> res = callCustomerServiceFacade.getTelRecordList(telDto);
				if (res.isSuccess()) {
					if (res.getEntity() != null) {
						dto.setLastCallTime(res.getEntity().get(0).getUpdateTime()); // 最后沟通时间
						callNum++; // 拨打成功后 拨打次数+1
						// telList = res.getEntity();
					}
				}
				dto.setCallNum(callNum + ""); // 沟通次数

				// 当状态为转客时，先转客
				if ("3".equals(dto.getStatus())) {
					if (StringUtils.isBlank(projectId)) {
						ar.setFailMsg("请选择项目");
						return ar;
					}
					// Response<CustomerDto> resCus = callCustomerService.addCustomer(dto,
					// projectId, telList);
					// if(!resCus.isSuccess()){
					// ar.setFailMsg(resCus.getResultMessage());
					// return ar;
					// }

					// 查询项目信息
					Response<Project> response = projectServiceFacade.findById(Long.parseLong(projectId));
					Project project = response.getEntity();
					dto.setProjectId(Long.parseLong(projectId));
					dto.setMerchantId(project.getMerchantId());
					dto.setAssignedType("0"); // 设置为未分配

					// 查询是否已存在
					CustomerDto cusDto = new CustomerDto();
					cusDto.setCustomerPhone(dto.getPhone());
					cusDto.setMerchantId(project.getMerchantId());
					cusDto.setProjectId(project.getId());
					cusDto.setDelFlag("0");
					ResponseList<Customer> resList = customerServiceFacade.selectCustomerPhoneByListPC(cusDto);
					if (resList.isSuccess()) {
						if (resList.getEntity() != null) {
							ar.setFailMsg("客户已存在");
							return ar;
						}
					}
				}

				Response<Integer> response = callCustomerServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用查看接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:delete"))) {
			try {
				Response<Integer> response = callCustomerServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(CallCustomerDto dto, Integer pageSize, Integer pageNum, String startTime, String endTime) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用分页查询接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:list"))) {
			try {
				// 当状态为待分配时，查询所有未拨打记录
				if ("0".equals(dto.getStatus())) {
					dto.setStatus("");
					dto.setCallNum("0");
					dto.addDesc("create_time");
				} else {
					dto.addDesc("update_time");
				}
				if (StringUtils.isNotBlank(startTime)) {
					startTime = startTime + " 00:00:00";
					dto.setUpdateTimeBefore(DateUtils.StringToDate(startTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				if (StringUtils.isNotBlank(endTime)) {
					endTime = endTime + " 23:59:59";
					dto.setUpdateTimeAfter(DateUtils.StringToDate(endTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}

				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				// 项目数据权限资源缓存
				dto.setPermissionUserId(user.getId());
				dto.setResourcesCode("menu_0015_0001");
				dto.setColumnName("maintain_user");

				Page<CallCustomerInfo> response = callCustomerServiceFacade.callFindPageByDto(dto,
						PageUtil.begin(pageNum, pageSize), pageSize, getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<CallCustomerInfo>());

					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 查询数量
	@RequestMapping(value = "getCount", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes getCount(CallCustomerDto dto, String startTime, String endTime) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用分页查询接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:list"))) {
			try {
				if (StringUtils.isNotBlank(startTime)) {
					startTime = startTime + " 00:00:00";
					dto.setUpdateTimeBefore(DateUtils.StringToDate(startTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				if (StringUtils.isNotBlank(endTime)) {
					endTime = endTime + " 23:59:59";
					dto.setUpdateTimeAfter(DateUtils.StringToDate(endTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				dto.addDesc("create_time");
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				// 项目数据权限资源缓存
				dto.setPermissionUserId(user.getId());
				dto.setResourcesCode("menu_0015_0001");
				dto.setColumnName("maintain_user");
				// 待跟进
				dto.setStatus("1");
				Response<Integer> count_1 = callCustomerServiceFacade.getCount(dto);
				// 无效
				dto.setStatus("2");
				Response<Integer> count_2 = callCustomerServiceFacade.getCount(dto);
				// 已分配
				dto.setStatus("3");
				Response<Integer> count_3 = callCustomerServiceFacade.getCount(dto);
				// 未拨
				dto.setStatus("");
				dto.setCallNum("0");
				Response<Integer> count_0 = callCustomerServiceFacade.getCount(dto);

				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("count_0", count_0.getEntity());
				map.put("count_1", count_1.getEntity());
				map.put("count_2", count_2.getEntity());
				map.put("count_3", count_3.getEntity());
				ar.setSucceed(map);
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	@RequestMapping(value = "calling")
	public String calling(HttpServletRequest request, ModelMap map) {
		map.put("id", request.getParameter("id"));
		map.put("caller", request.getParameter("caller"));
		map.put("list", request.getParameter("callList"));
		return "/call/calling";
	}

	// 查询历史通话记录
	@RequestMapping(value = "telRecordList", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes telRecordList(TelRecordDto entity) {
		AjaxRes ar = getAjaxRes();

		try {
			entity.setCallStatus("1"); // 只查询接通的记录
			entity.setRelationType("1");
			entity.addDesc("create_time");
			ResponseList<TelRecordDto> response = callCustomerServiceFacade.getTelRecordList(entity);
			if (response.isSuccess()) {
				ar.setSucceed(response);
			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}

	// 项目列表
	@RequestMapping(value = "projects", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes projects() {
		AjaxRes ar = getAjaxRes();
		// 数据权限
		User user = ShiroUtil.getCurrentUser();
		CustomerComponentDto dto = new CustomerComponentDto();
		dto.setPermissionUserId(user.getId());
		dto.setMerchantId(user.getMerchantId());
		dto.setOrders(" t.create_time desc ");
		List<Project> projects = customerServiceFacade.findProjectByDto(dto).getEntity();
		com.alibaba.fastjson.JSONArray dtArray = new com.alibaba.fastjson.JSONArray();
		if (projects != null && projects.size() != 0) {
			for (Project project : projects) {
				JSONObject row = new JSONObject();
				row.put("id", project.getId());
				row.put("projectName", project.getProjectName());
				dtArray.add(row);
			}
		}
		ar.setSucceed(dtArray);
		return ar;
	}

	// 新增返回实体对象
	@RequestMapping(value = "callPhone", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes callPhone(HttpServletRequest request, TelRecordDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限 2.调用分页查询接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:callPhone"))) {
			try {
				// 当主叫号码为空时，弹出提示
				if (StringUtils.isBlank(dto.getCaller())) {
					ar.setFailMsg("未获取到主叫电话，请重试");
					return ar;
				}
				if (StringUtils.isBlank(dto.getCalled())) {
					ar.setFailMsg("未获取到客户电话，请重试");
					return ar;
				}

				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());// 商户ID
				dto.setCreateUserId(user.getId());// 用户ID
				dto.setCallType("0");// 通话类型:0：呼出；1：呼入
				dto.setTerminalType("0");// 终端类型:0：PC；1：手机；3:座机
				Response<TelRecordDto> response = callCustomerServiceFacade.callPhone(dto);

				if (response.isSuccess()) {
					ar.setSucceed(dto);
				} else {
					ar.setFailMsg("电话拨打失败");
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg("电话拨打失败");
			}
		}
		return ar;
	}

	@RequestMapping(value = "distribution")
	public String distribution(ModelMap map, String ids) {
		map.put("ids", ids);
		return "/call/distribution";
	}

	@RequestMapping(value = "saveDistribution")
	@ResponseBody
	public AjaxRes saveDistribution(String ids, Long userId) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		String[] idsArray = ids.split(",");
		for (String id : idsArray) {
			CallCustomerDto dto = new CallCustomerDto();
			dto.setId(Long.valueOf(id));
			dto.setMaintainUser(userId);
			dto.setUpdateTime(new Date());
			dto.setUpdateUserId(user.getId());
			callCustomerServiceFacade.updateByPrimaryKey(dto, true);
		}
		ar.setSucceedMsg("分配成功");
		;
		return ar;
	}

	// 拨打明细
	@RequestMapping(value = "callDetail")
	public String callDetail(HttpServletRequest request, ModelMap map) {
		map.put("id", request.getParameter("id"));
		return "/call/call_detail";
	}

	// 导出记录
	@RequestMapping(value = "expExcel")
	public void expExcel(CallCustomerDto dto, String startTime, String endTime, String[] expIds,
			HttpServletResponse response) {
		/*
		 * 1.判断权限 2.调用分页查询接口 3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:callCustomer:expExcel")) {
			try {
				if (StringUtils.isNotBlank(startTime)) {
					startTime = startTime + " 00:00:00";
					dto.setUpdateTimeBefore(DateUtils.StringToDate(startTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				if (StringUtils.isNotBlank(endTime)) {
					endTime = endTime + " 23:59:59";
					dto.setUpdateTimeAfter(DateUtils.StringToDate(endTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				dto.addDesc("create_time");
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				// 项目数据权限资源缓存
				dto.setPermissionUserId(user.getId());
				dto.setResourcesCode("menu_0015_0001");
				dto.setColumnName("maintain_user");

				// 定义标签数字
				String[] title = new String[] { "未拨", "待跟进", "无效", "已转客" };
				// 当传入的Id不为空时，导出对应的标签列,否则导出所有
				List<String> list = new ArrayList<String>();
				if (expIds == null || expIds.length == 0) {
					for (int b = 0; b < title.length; b++) {
						list.add(title[b]);
					}
				} else {
					list.add(title[Integer.parseInt(dto.getStatus())]);
					String expId = "";
					for (int b = 0; b < expIds.length; b++) {
						expId += " id='" + expIds[b] + "' or";
					}
					if (!"".equals(expId)) {
						expId = expId.substring(0, expId.length() - 3);
						dto.setSql(expId);
					}
				}

				download(dto, list, response);

			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
	}

	public void download(CallCustomerDto dto, List<String> list, HttpServletResponse response) {
		try {
			@SuppressWarnings("resource")
			HSSFWorkbook wb = new HSSFWorkbook();
			for (int b = 0; b < list.size(); b++) {
				HSSFSheet sheet = wb.createSheet(list.get(b));
				HSSFCellStyle headStyle = wb.createCellStyle();
				HSSFFont f = wb.createFont();
				f.setFontHeightInPoints((short) 11);// 字号
				f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
				headStyle.setFont(f);
				headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
				headStyle.setBorderBottom((short) 1);
				headStyle.setBorderRight((short) 1);
				headStyle.setFillBackgroundColor((short) 20);
				HSSFRow row = sheet.createRow((int) 0);
				// 创建单元格，并设置值表头 设置表头居中
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
				style.setBorderBottom((short) 1);
				style.setBorderRight((short) 1);
				String[] header = new String[] { "序号", "客户姓名", "联系电话", "导入时间", "维护人", "到访时间", "关注问题", "失败原因", "备注",
						"说明", "最后一次通话时间", "沟通次数" };
				for (int i = 0; i < header.length; i++) {
					HSSFCell cell = row.createCell(i);
					cell.setCellStyle(style);
					HSSFRichTextString text = new HSSFRichTextString(header[i]);
					cell.setCellValue(text);
				}

				if (StringUtils.isBlank(dto.getSql())) {
					dto.setStatus(b + "");
				}
				if ("0".equals(dto.getStatus())) {
					dto.setStatus("");
					dto.setCallNum("0");
				} else {
					dto.setCallNum("");
				}
				ResponseList<CallCustomerInfo> reslist = callCustomerServiceFacade.setValueGetList(dto);
				if (reslist.isSuccess() && reslist.getEntity() != null && reslist.getEntity().size() > 0) {
					HSSFCell cell = null;
					for (int j = 0; j < reslist.getEntity().size(); j++) {
						row = sheet.createRow((int) j + 1);
						CallCustomerInfo info = reslist.getEntity().get(j);
						cell = row.createCell(0, 1);
						cell.setCellValue(j + 1);
						cell = row.createCell(1, 1);
						cell.setCellValue(StringUtils.isBlank(info.getUserName()) ? "" : info.getUserName());
						cell = row.createCell(2, 1);
						cell.setCellValue(StringUtils.isBlank(info.getPhone()) ? "" : info.getPhone());
						cell = row.createCell(3, 1);
						cell.setCellValue(DateUtils.DateToString(info.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
						cell = row.createCell(4, 1);
						cell.setCellValue(info.getMaintainUserName());
						cell = row.createCell(5, 1);
						cell.setCellValue(DateUtils.DateToString(info.getVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
						cell = row.createCell(6, 1);
						cell.setCellValue(info.getConcern());
						cell = row.createCell(7, 1);
						cell.setCellValue(info.getFailure());
						cell = row.createCell(8, 1);
						cell.setCellValue(info.getRemark());
						cell = row.createCell(9, 1);
						cell.setCellValue(info.getCaption());
						cell = row.createCell(10, 1);
						cell.setCellValue(
								DateUtils.DateToString(info.getLastCallTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
						cell = row.createCell(11, 1);
						cell.setCellValue(info.getCallNum());
					}
				}
			}

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String mimetype = "application/x-msdownload";
			String downFileName = "excel-" + df.format(new Date()) + ".xls";
			String inlineType = "attachment";
			response.setHeader("Content-Disposition", inlineType + ";filename=\"" + downFileName + "\"");
			OutputStream out = response.getOutputStream();
			response.setContentType(mimetype);
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 分页查询已转客未分配记录
	@RequestMapping(value = "getWeifenpeiPageModel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes getWeifenpeiPageModel(HttpServletRequest request, Integer pageSize, Integer pageNum,
			String startTime, String endTime) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限 2.调用分页查询接口 3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:distribution:list"))) {
			try {
				CallCustomerDto dto = new CallCustomerDto();
				dto.addDesc("create_time");

				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				// 项目数据权限资源缓存
				dto.setPermissionUserId(user.getId());
				dto.setResourcesCode("menu_0015_0001");
				dto.setColumnName("maintain_user");

				// 判断项目是否为空
				String projectId = request.getParameter("wfpProjectId");
				if (StringUtils.isBlank(projectId)) {
					ar.setFailMsg("项目不能为空");
					return ar;
				}
				dto.setProjectId(Long.parseLong(projectId));
				Page<CallCustomerInfo> response = callCustomerServiceFacade.getWeifenpeiPageModel(dto,
						PageUtil.begin(pageNum, pageSize), pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<CallCustomerInfo>());

					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}
}
